package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 案例拓展：实现群聊
 */
public class Client {
    public static void main(String[] args) throws Exception {
        //1.创建客户端对象
        Socket socket = new Socket("127.0.0.1", 8888);
        System.out.println("客户端已经启动....");
        Scanner sc = new Scanner(System.in);
        //2.创建流，把数据写入服务器
        OutputStream os = socket.getOutputStream();
        //3.使用特殊数据流包装输出流
        DataOutputStream dos = new DataOutputStream(os);

        InputStream is = socket.getInputStream();
        DataInputStream dis = new DataInputStream(is);



        new Thread() {
            @Override
            public void run() {
                while (true) {
                    //输入数据
                    System.out.println("请输入：");
                    String message = sc.next();
                    //判断 如果输入exit那么退出
                    if ("exit".equals(message)) {
                        System.out.println("=====客户端退出=====");
                        break;
                    }
                    //4.把数据写入服务器
                    try {
                        dos.writeUTF(message);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    try {
                        dos.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                //创建输入流接收
                while (true) {
                    String msg = null;
                    try {
                        msg = dis.readUTF();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("群里有人发送：" + msg);
                }
            }
        }.start();





    }




}
